package cn.tedu.ems.service.impl;

import cn.tedu.ems.mapper.LoginMapper;
import cn.tedu.ems.pojo.entity.User;
import cn.tedu.ems.pojo.vo.Manager;
import cn.tedu.ems.pojo.vo.UserLogin;
import cn.tedu.ems.pojo.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
//这里是通过用户名查询数据库，返回一个UserDetails对象
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("这是一个用户名username:{}",username);
        //查询
        QueryWrapper<UserVO> userQueryWrapper = new QueryWrapper<>();
        //根据用户名查询username,password,status,id
        userQueryWrapper.select("id","username","password","status");
        userQueryWrapper.eq("username",username);
        UserVO userVO = loginMapper.selectOne(userQueryWrapper);


        log.debug("userVO:{}",userVO);

        if (Objects.isNull(userVO)){
            throw new UsernameNotFoundException("用户不存在");
        }
        //这里查看用户是否被禁用
        if("-1".equals(userVO.getStatus())){
            throw new UsernameNotFoundException("用户被禁用");
        }

        User user = new User();
        BeanUtils.copyProperties(userVO,user);
        log.debug("user:{}",user);

        return new UserLogin(user);
    }



}
